//
//  LoginController.m
//  MClient
//
//  Created by Wang Fei on 10-5-11.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//


#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CoreTelephonyDefines.h>


#import "LoginController.h"
#import "SettingController.h"
#import "AccountController.h"
#import "AboutController.h"
#import "DemoController.h"
#import "MServerJsonDAO.h"
#import "MServerDAO.h"
#import "MServerConfigCache.h"
#import "MCFunction.h"
#import "UIImageAdditions.h"
#import "MenuController.h"
#import "MCTabBarController.h"
#import "LoginCheckController.h"
#import "UIDevice+IdentifierAddition.h"
@implementation MCLoginView
@synthesize delegate = _delegate;
@synthesize partyIdField = _partyIdField;
@synthesize userIdField = _userIdField;
@synthesize pWordField = _pWordField;
@synthesize tableView = _tableView;
- (void)dealloc {
	[_tableView release];
	[_loginButton release];
	[_settingButton release];
	[_pWordField release];
	[_partyIdField release];
	[_pWordField release];
	[super dealloc];
}

- (id)initWithPoint:(CGPoint)point
{
	CGRect frame = CGRectMake(point.x, point.y, kLoginFormBackgroundWidth, kLoginFormBackgroundHeight_Demo);//kLoginFormBackgroundWidth等是login工作内容区的大小定义。
	if (self = [super initWithFrame:frame]) {
		_tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
		_tableView.backgroundColor = [UIColor clearColor];
		_tableView.allowsSelection = NO;
		_tableView.scrollEnabled = NO;
		_tableView.dataSource = self;
		_tableView.delegate = self;
		_tableView.separatorColor = self.tableSeparatorColor;
		
#pragma mark---------白菜2013-2-4-----------ios6渲染兼容------------
        _tableView.backgroundView = nil;
        
		if ([MCUserDefaults instance].isHidePartyId) {//隐藏会员名
			_partyIdField = [[UITextField alloc] initWithFrame:CGRectZero];
			_partyIdField.text = [MCUserDefaults instance].current_PartyId;
		}
	}
	
	return self;
}

- (UIButton*)addButton:(CGRect)frame withImage:(UIImage*)aImage withDelegate:(id)delegate withSelector:(SEL)selector
{
	UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
	btn.frame = frame;
	btn.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
	[btn setBackgroundImage:aImage/*[aImage scaleToSize:frame.size]*/ forState:UIControlStateNormal];
	[btn addTarget:delegate action:selector forControlEvents:UIControlEventTouchUpInside];
	
	return [btn retain];
}

- (UIButton*)addButton:(CGRect)frame withImage:(UIImage*)aImage withSelector:(SEL)selector
{
	UIButton* btn = [self addButton:frame withImage:aImage withDelegate:_delegate withSelector:selector];
	[self addSubview:btn];
	return btn;
}

- (UILabel*)addLabel:(CGRect)frame withTitle:(NSString*)aTitle
{
	UILabel* label = [[UILabel alloc] initWithFrame:frame];
	label.text = aTitle;
	label.textAlignment = UITextAlignmentLeft;
	label.font = [UIFont boldSystemFontOfSize:18];
	label.textColor = self.tableCellTitleColor;
	label.backgroundColor = [UIColor clearColor];
	return label;
}

- (UITextField*)addTextField:(CGRect)frame withPlaceholder:(NSString*)aText
{
	UITextField *field = [[UITextField alloc] initWithFrame:frame];
	field.placeholder = aText;
	field.clearsOnBeginEditing = NO;
	field.returnKeyType = UIReturnKeyDone;
	field.textColor = self.tableCellContentColor;
	field.borderStyle = UITextBorderStyleNone;
	field.font = [UIFont boldSystemFontOfSize:18.0];
	[field addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
	
	return field;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 40;
}

//TableView的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if ([MCUserDefaults instance].isHidePartyId) {//隐藏会员名
		return 2;
	} else {//非隐藏会员名
		return 3;
	}
}

- (float) getCellAlpha {
	return 1.0;//0.7;
}

- (NSString *)getPartyLabel {
	return @"会员:";
}

- (NSString *)getUserNameLabel {
	return @"用户:";
}

- (NSString *)getPasswordLabel {
	return @"密码:";
}

- (NSString *)getPartyHolder {
	return @"请输入您的会员名";
}

- (NSString *)getUserNameHolder {
	return @"请输入您的用户名";
}

- (NSString *)getPasswordHolder {
	return @"请输入您的密码";
}

- (UIColor*)tableCellBgColor {
	return [[UIColor whiteColor] colorWithAlphaComponent:[self getCellAlpha]];
}

- (UIColor*)tableSeparatorColor {
	return [UIColor grayColor];
}
- (UIColor*)tableCellTitleColor {
	return [UIColor blackColor];
}
- (UIColor*)tableCellContentColor {
	return [UIColor colorWithRed:0.282 green:0.341 blue:0.455 alpha:1];
}

//初始化TableVie根据参数和数据绘制每一行以及填充数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	NSString* identifier = [NSString stringWithFormat:@"loginTableCell-%d-%d", indexPath.section, indexPath.row];
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
	
	if (cell == nil) {
		UILabel* titleLabel = nil;
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:identifier] autorelease];
		if ([MCUserDefaults instance].isHidePartyId) {
			[cell.contentView addSubview:indexPath.row==0 ?
			 (titleLabel = [self addLabel:CGRectMake(10, 10, 80, 25) withTitle:[self getUserNameLabel]]) : 
			 (titleLabel = [self addLabel:CGRectMake(10, 10, 80, 25) withTitle:[self getPasswordLabel]])];
			[cell.contentView addSubview:indexPath.row==0?
			 (_userIdField = [self addTextField:CGRectMake(80, 10, 180, 25) withPlaceholder:[self getUserNameHolder]]) : 
			 (_pWordField  = [self addTextField:CGRectMake(80, 10, 180, 25) withPlaceholder:[self getPasswordHolder]])];
		} else {
			[cell.contentView addSubview:indexPath.row==0 ?
			 (titleLabel = [self addLabel:CGRectMake(10, 10, 80, 25) withTitle:[self getPartyLabel]]) : indexPath.row==1 ?
			 (titleLabel = [self addLabel:CGRectMake(10, 10, 80, 25) withTitle:[self getUserNameLabel]]) :
			 (titleLabel = [self addLabel:CGRectMake(10, 10, 80, 25) withTitle:[self getPasswordLabel]])];
			[cell.contentView addSubview:indexPath.row==0 ?
			 (_partyIdField = [self addTextField:CGRectMake(80, 10, 180, 25) withPlaceholder:[self getPartyHolder]]) : indexPath.row==1 ?
			 (_userIdField  = [self addTextField:CGRectMake(80, 10, 180, 25) withPlaceholder:[self getUserNameHolder]]) :
			 (_pWordField   = [self addTextField:CGRectMake(80, 10, 180, 25) withPlaceholder:[self getPasswordHolder]])];
		}
		_partyIdField.text = [MCUserDefaults instance].current_PartyId;
		_userIdField.text = [MCUserDefaults instance].current_UserId;
		_pWordField.text = [MCUserDefaults instance].current_Password;
		titleLabel.tag = -1;
	}
	cell.backgroundColor = self.tableCellBgColor;
	_partyIdField.textColor = self.tableCellContentColor;
	_userIdField.textColor = self.tableCellContentColor;
	_pWordField.textColor = self.tableCellContentColor;
	((UILabel*)[cell viewWithTag:-1]).textColor = self.tableCellTitleColor;
	
	_pWordField.secureTextEntry = YES;
	
	return cell;
}

- (void)refreshImages
{
	MCUserDefaults* defaults = [MCUserDefaults instance]; 
	// 更新背景图片
	[_loginButton setBackgroundImage:defaults.skin_btnLoginImg forState:UIControlStateNormal];
	[_settingButton setBackgroundImage:defaults.skin_btnConfigImg forState:UIControlStateNormal];
	_tableView.separatorColor = self.tableSeparatorColor;
	[_tableView reloadData];
}

- (void)refreshTextField:(NSArray*)aValues
{
	int nCount = [aValues count];
	self.partyIdField.text = nCount>0 ? [aValues objectAtIndex:0] : @"";
	self.userIdField.text = nCount>1 ?[aValues objectAtIndex:1] : @"";
	self.pWordField.text = nCount>2 ? [aValues objectAtIndex:2] : @"";
}

- (void) textFieldDone:(id)sender
{
	[sender resignFirstResponder];
}

//- (void)switchValueChange:(id)sender
//{
//	MCUserDefaults* defaults = (MCUserDefaults*)[MCUserDefaults instance]; 
//	UIView* switchCtrl = (UIView*)sender;
//	if (switchCtrl.tag == -198) {
//		defaults.isSavePassword = !defaults.isSavePassword;
//	} else {
//		defaults.isSavePassword = !defaults.isAutoLogin;
//		defaults.isAutoLogin = !defaults.isAutoLogin;
//	}
//}

- (void)switchValueChange:(id)sender
{
	MCUserDefaults* defaults = (MCUserDefaults*)[MCUserDefaults instance]; 
	UIButton* switchCtrl = (UIButton*)sender;
	if (switchCtrl.tag == -198) {
		if (defaults.isSavePassword) {
			defaults.isSavePassword = !defaults.isSavePassword;
			defaults.isAutoLogin = NO;
		} else {
			defaults.isSavePassword = !defaults.isSavePassword;
		}
	} else {
		if (!defaults.isAutoLogin) {
			defaults.isSavePassword = YES;
			defaults.isAutoLogin = !defaults.isAutoLogin;
		} else {
			defaults.isAutoLogin = !defaults.isAutoLogin;
		}
	}
	
	UIImageView* savePassWord = (UIImageView*)[[self viewWithTag:-198] viewWithTag:-1];
	UIImageView* autoLogin = (UIImageView*)[[self viewWithTag:-199] viewWithTag:-1];
	
	UIImage* image = defaults.isAutoLogin ? [UIImage imageNamed:@"select2.png"] : 
	defaults.isSavePassword ? [UIImage imageNamed:@"select2.png"] : [UIImage imageNamed:@"select1.png"];
	savePassWord.image = image;
	
	image = defaults.isAutoLogin ? [UIImage imageNamed:@"select2.png"] : [UIImage imageNamed:@"select1.png"];
	autoLogin.image = image;
}
@end

@implementation MCDemoLoginView
- (void)dealloc {
	[_accountButton release];
	[_demoButton release]; 
	[super dealloc];
}

- (id)initWithPoint:(CGPoint)point withDelegate:(id)delegate
{
	if (self = [super initWithPoint:point]) {
		MCUserDefaults* defaults = [MCUserDefaults instance];
		int nWidth = CGRectGetWidth(self.bounds);
		_tableView.frame = defaults.isHidePartyId ? CGRectMake(-5, 30, nWidth+10, 100):CGRectMake(-5, 0, nWidth+10, 145);
		_tableView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
		[self addSubview:_tableView];
		self.delegate = delegate;
		
		int nStepY = defaults.isHidePartyId ? 15 : 15;
		int nPoxY = CGRectGetMaxY(_tableView.frame) + nStepY;
		//UIButton登录按钮＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
		_loginButton = [self addButton:CGRectMake(0,nPoxY,nWidth,40) withImage:defaults.skin_btnLoginImg withSelector:@selector(doLogin)];
		
		nPoxY += CGRectGetHeight(_loginButton.frame) + nStepY;
		//UIButton已有帐号按钮＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
		_accountButton = [self addButton:CGRectMake(0,nPoxY,64,69) withImage:defaults.skin_btnAccountImg withSelector:@selector(showAccount:)];
		//UIButton高级设置按钮＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
		_settingButton = [self addButton:CGRectMake(72,nPoxY,64,69) withImage:defaults.skin_btnConfigImg withSelector:@selector(showPreferences:)];
		//UIButton演示应用按钮＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
		_demoButton = [self addButton:CGRectMake(144,nPoxY,64,69) withImage:defaults.skin_btnDemoImg withSelector:@selector(showDemo:)];
		//UIButton关于按钮＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
		_aboutButton = [self addButton:CGRectMake(216,nPoxY,64,69) withImage:defaults.skin_btnAboutImg withSelector:@selector(showHelp:)];
	}
	return self;
}

- (void)refreshImages
{
	[super refreshImages];
	MCUserDefaults* defaults = [MCUserDefaults instance]; 
	// 更新背景图片
	[_accountButton setBackgroundImage:defaults.skin_btnAccountImg forState:UIControlStateNormal];
	[_demoButton setBackgroundImage:defaults.skin_btnDemoImg forState:UIControlStateNormal];
	[_aboutButton setBackgroundImage:defaults.skin_btnAboutImg forState:UIControlStateNormal];
}

@end
@implementation MCAppLoginView

//- (id)initWithPoint:(CGPoint)point withDelegate:(id)delegate
//{
//	if (self = [super initWithPoint:point]) {
//		MCUserDefaults* defaults = [MCUserDefaults instance];
//		int nWidth = CGRectGetWidth(self.bounds);
//		_tableView.frame = defaults.isHidePartyId ? CGRectMake(-5, 0, nWidth+10, 100):CGRectMake(-5, 0, nWidth+10, 145);
//		[self addSubview:_tableView];
//		self.delegate = delegate;
//		
//		//int nStepY = [self getNStepY];
//		int nStepY = defaults.isHidePartyId ? 10 : 10;
//		int nPoxY = CGRectGetMaxY(_tableView.frame) + nStepY;
//		_loginButton = [self addButton:CGRectMake(0,nPoxY,176,46) withImage:defaults.skin_btnLoginImg withSelector:@selector(doLogin)];
//		_settingButton = [self addButton:CGRectMake(184,nPoxY,96,46) withImage:defaults.skin_btnConfigImg withSelector:@selector(showPreferences:)];
//		
//		UILabel* label = [self addLabel:CGRectMake(10, nPoxY+15+46, 80, 26) withTitle:@"记住密码"];
//		label.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
//		label.textColor = [UIColor colorWithRed:0 green:153/255.0 blue:204/255.0 alpha:1.0];
//		[self addSubview:label];
//		UISwitch* pWordSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(180, nPoxY+15+46, 92, 26)];
//		pWordSwitch.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
//		[pWordSwitch addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventValueChanged];
//		pWordSwitch.on = defaults.isSavePassword;
//		pWordSwitch.tag = -198;
//		[self addSubview:pWordSwitch];
//		[pWordSwitch release];
//		
//		label = [self addLabel:CGRectMake(10, nPoxY+50+46, 80, 26) withTitle:@"自动登录"];
//		label.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
//		label.textColor = [UIColor colorWithRed:0 green:153/255.0 blue:204/255.0 alpha:1.0];
//		[self addSubview:label];
//		UISwitch* autoLoginSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(180, nPoxY+50+46, 92, 26)];
//		autoLoginSwitch.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
//		[autoLoginSwitch addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventValueChanged];
//		autoLoginSwitch.on = defaults.isAutoLogin;
//		autoLoginSwitch.tag = -199;
//		[self addSubview:autoLoginSwitch];
//		[autoLoginSwitch release];
//	}
//	return self;
//}

- (id)initWithPoint:(CGPoint)point withDelegate:(id)delegate
{
	if (self = [super initWithPoint:point]) {
		MCUserDefaults* defaults = [MCUserDefaults instance];
		int nWidth = CGRectGetWidth(self.bounds);
		_tableView.frame = defaults.isHidePartyId ? CGRectMake(-5, 0, nWidth+10, 100):CGRectMake(-5, 0, nWidth+10, 145);
		[self addSubview:_tableView];
		self.delegate = delegate;
		
		//int nStepY = [self getNStepY];
		int nStepY = defaults.isHidePartyId ? 10 : 10;
		int nPoxY = CGRectGetMaxY(_tableView.frame) + nStepY;
		_loginButton = [self addButton:CGRectMake(0,nPoxY+50,176,46) withImage:defaults.skin_btnLoginImg withSelector:@selector(doLogin)];
		_settingButton = [self addButton:CGRectMake(184,nPoxY+50,96,46) withImage:defaults.skin_btnConfigImg withSelector:@selector(showPreferences:)];
		
//		UIImage* image = defaults.isAutoLogin ? [UIImage imageNamed:@"select2.png"] : 
//		defaults.isSavePassword ? [UIImage imageNamed:@"select2.png"] : [UIImage imageNamed:@"select1.png"];
//		UIButton* check = [self addButton:CGRectMake(15, nPoxY+5, 16, 16) withImage:image withDelegate:self withSelector:@selector(switchValueChange:)];
//		check.tag = -198;
//		[self addSubview:check];
//		[check release];
//		UILabel* label = [self addLabel:CGRectMake(34, nPoxY, 80, 26) withTitle:@"记住密码"];
//		label.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
//		label.textColor = [UIColor blackColor];
//		[self addSubview:label];
//		
//		image = defaults.isAutoLogin ? [UIImage imageNamed:@"select2.png"] : [UIImage imageNamed:@"select1.png"];
//		check = [self addButton:CGRectMake(170, nPoxY+5, 16, 16) withImage:image withDelegate:self withSelector:@selector(switchValueChange:)];
//		check.tag = -199;
//		[self addSubview:check];
//		[check release];
//		label = [self addLabel:CGRectMake(188, nPoxY, 80, 26) withTitle:@"自动登录"];
//		label.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
//		label.textColor = [UIColor blackColor];
//		[self addSubview:label];
		
		UIButton* boundButton = [UIButton buttonWithType:UIButtonTypeCustom];
		boundButton.frame = CGRectMake(20, nPoxY, 150, 26);
		boundButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
		[boundButton addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventTouchUpInside];
		boundButton.tag = -198;
		
		UIImage* image = defaults.isAutoLogin ? [UIImage imageNamed:@"select2.png"] : 
		defaults.isSavePassword ? [UIImage imageNamed:@"select2.png"] : [UIImage imageNamed:@"select1.png"];
		UIImageView* check = [[UIImageView alloc] initWithFrame:CGRectMake(0, 4, 16, 16)];check.image = image;
		check.tag = -1;
		[boundButton addSubview:check];
		[check release];
		UILabel* label = [self addLabel:CGRectMake(20, 0, 77, 26) withTitle:@"记住密码"];
		label.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
		label.textColor = [MCFunction hexColor:@"27322F64"];
		[boundButton addSubview:label];
		[label release];
		[self addSubview:boundButton];
		
		boundButton = [UIButton buttonWithType:UIButtonTypeCustom];
		boundButton.frame = CGRectMake(170, nPoxY, 150, 26);
		boundButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
		[boundButton addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventTouchUpInside];
		boundButton.tag = -199;
		
		image = defaults.isAutoLogin ? [UIImage imageNamed:@"select2.png"] : [UIImage imageNamed:@"select1.png"];
		check = [[UIImageView alloc] initWithFrame:CGRectMake(0, 4, 16, 16)];check.image = image;
		check.tag = -1;
		[boundButton addSubview:check];
		[check release];
		label = [self addLabel:CGRectMake(20, 0, 77, 26) withTitle:@"自动登录"];
		label.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
		label.textColor = [MCFunction hexColor:@"27322F64"];
		[boundButton addSubview:label];
		[label release];
		[self addSubview:boundButton];
	}
	return self;
}

- (NSInteger)getNStepY {
	MCUserDefaults* defaults = [MCUserDefaults instance];
	return defaults.isHidePartyId ? 25 : 15;
}

- (void)refreshImages
{
	[super refreshImages];
	
	MCUserDefaults* defaults = [MCUserDefaults instance];
	UIImageView* savePassWord = (UIImageView*)[[self viewWithTag:-198] viewWithTag:-1];
	UIImageView* autoLogin = (UIImageView*)[[self viewWithTag:-199] viewWithTag:-1];
	
	if (savePassWord) {
		UIImage* image = defaults.isAutoLogin ? [UIImage imageNamed:@"select2.png"] : 
		defaults.isSavePassword ? [UIImage imageNamed:@"select2.png"] : [UIImage imageNamed:@"select1.png"];
		savePassWord.image = image;
	}
	if (autoLogin) {
		UIImage* image = defaults.isAutoLogin ? [UIImage imageNamed:@"select2.png"] : [UIImage imageNamed:@"select1.png"];
		autoLogin.image = image;
	}
}
@end


@interface LoginController (Private)
- (void)doLogin;
- (void)defaultInit;
- (void)autoLoginInit;
@end


@implementation LoginController
@synthesize loginView;

- (void)defaultInit
{
	// 顶部导航栏======================================
	//[self.navigationController setNavigationBarHidden:YES animated:NO];
	self.title = [[MClientAppDelegate getInfoDictionary] objectForKey:@"CFBundleDisplayName"];
	self.navigationItem.hidesBackButton = YES;
	
	// 用作背景的UIView================================
	UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];  
	backgroundView.image = self.userDefaults.skin_bgLoginImg; 
	backgroundView.tag = -100;
	backgroundView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
	[self.view addSubview:backgroundView];
	[self.view sendSubviewToBack:backgroundView];
	[backgroundView release]; 
	// 用一个UINavigationBar以便于再push到下一页面时隐藏navigationcontroller自带的UINavigationBar时最顶上出现白边
	UINavigationBar* naviBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, -navigationBarHeight, self.width, navigationBarHeight)];
	naviBar.tintColor = self.userDefaults.skin_navigationBarColor;
	naviBar.tag = -200;
	naviBar.hidden = YES;
	UILabel* title = [[[UILabel alloc] initWithFrame:naviBar.bounds] autorelease];
	title.backgroundColor = [UIColor clearColor];
	title.text = self.title;
	title.textAlignment = UITextAlignmentCenter;
	title.textColor = [UIColor whiteColor];
	title.font = [UIFont boldSystemFontOfSize:20];
	[naviBar addSubview:title];
	[self.view addSubview:naviBar];
	
	UIImage* logo = self.userDefaults.skin_loginlogoImg;
	CGSize size = [logo size];
	UIImageView *logoImageView = [[UIImageView alloc] init];
	logoImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
	// 横屏状态
	if (self.width > self.height) {
		logoImageView.frame = CGRectMake((self.width-size.width)/2, self.height-size.height-5, size.width, size.height);
	} else {
		logoImageView.frame = CGRectMake((self.width-size.width)/2, self.height-size.height-10, size.width, size.height);
	}
	logoImageView.image = logo; 
	logoImageView.tag = -1;
	[self addImageSubView:logoImageView];
	[logoImageView release]; 
	
	size = [self.userDefaults.skin_logintitleImg size];
	UIImageView *titleImageView = [[UIImageView alloc] init]; 
	titleImageView.tag = -2;
	titleImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
	// 横屏状态
	if (self.width > self.height) {
		titleImageView.frame = CGRectMake((self.width-size.width)/2, 10, size.width, size.height);
	} else {
		titleImageView.frame = CGRectMake((self.width-size.width)/2, 20, size.width, size.height);
	}
	titleImageView.image = self.userDefaults.skin_logintitleImg; 
	[self addImageSubView:titleImageView];
	[titleImageView release]; 
	
	Class class;
	if (self.userDefaults.isDemoApplication) {
		class = [[MCUserDefaults instance] class:@"MCDemoLoginView"];
		loginViewHeight = kLoginFormBackgroundHeight_Demo;
	} else{
		class = [MCAppLoginView class];
		loginViewHeight = kLoginFormBackgroundHeight_Demo;//loginViewHeight = kLoginFormBackgroundHeight_Demo;huotianjun修改
	}
	if ([self.view viewWithTag:-101]) {
		[[self.view viewWithTag:-101] removeFromSuperview];
	}
	// 横屏状态
	if (self.width > self.height) {
		[self.view addSubview:loginView = [[class alloc] initWithPoint:CGPointMake((self.width-kLoginFormBackgroundWidth)/2, self.height-loginViewHeight-50) 
														  withDelegate:self]];
	} else {
		[self.view addSubview:loginView = [[class alloc] initWithPoint:CGPointMake((self.width-kLoginFormBackgroundWidth)/2, (self.height-loginViewHeight)/2) 
														  withDelegate:self]];
	}
	loginView.tag = -101;
	loginView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
	[loginView refreshTextField:fieldValues];
}

- (void)addImageSubView:(UIView *) view{
	[self.view addSubview:view];
}

- (void)autoLoginInit
{
	BOOL isLandscape = NO;
	if (self.width > self.height) {
		isLandscape = YES;
	}
	imgDefault = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
	imgDefault.image = [UIImage imageNamed:isLandscape?@"Default.png":@"Default.png"];  
	//imgDefault.frame = CGRectMake(0, 0, self.width, self.height);
	//imgDefault.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
	
	[self.view addSubview:imgDefault];
	[self.view bringSubviewToFront:imgDefault];
}

- (void)reloadFieldValues
{
	[fieldValues release];
	
	if (self.userDefaults.isSavePassword) {
		fieldValues = [[NSMutableArray alloc] 
					   initWithObjects:self.userDefaults.current_PartyId, 
					   self.userDefaults.current_UserId, 
					   self.userDefaults.current_Password, nil];
	} else {
		fieldValues = [[NSMutableArray alloc] 
					   initWithObjects:self.userDefaults.current_PartyId, 
					   self.userDefaults.current_UserId, @"", nil];
	}
	[loginView refreshTextField:fieldValues];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (int)identiferId {
	return 0;
}
- (void)hidePartyId {
}

- (void)viewDidLoad {
    NSLog(@"登陆界面 开始");
// 得到sim卡号的方法
//    [UIDevice currentDevice].uniqueIdentifier
//(NSString*)CTSIMSupportCopyMobileSubscriberIdentity(nil);
//    NSString *imsi = (NSString*)CTSIMSupportCopyMobileSubscriberIdentity(nil);
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"IMSI" 
//                                                    message:imsi 
//                                                   delegate:self 
//                                          cancelButtonTitle:@"OK" 
//                                          otherButtonTitles:nil];
//    [alert show];
//    [alert release];

	[super viewDidLoad];
	[self hidePartyId];
	[self reloadFieldValues];
	// 设置了自动登录，直接登录
	if (self.userDefaults.isAutoLogin) {
		bAutoLogin = YES;
		[self autoLoginInit];
		[self viewWillAppear:NO];
		[self doLogin];
	} else {
		bAutoLogin = NO;
		[self defaultInit];
	}
	statJsonDao = [[loginStat alloc] init];
}

- (void)hideNavigationBar {
	//[self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];

	self.navigationController.navigationBar.tintColor = self.userDefaults.skin_navigationBarColor;
    
    [self reloadFieldValues];//huotianjun
	
	if (loginView) {
		UINavigationBar* naviBar = (UINavigationBar*)[self.view viewWithTag:-200];
		naviBar.tintColor = self.navigationController.navigationBar.tintColor;
		naviBar.hidden = YES;
		
		bViewWillApper = YES;
		[self didRotateFromInterfaceOrientation:0];
		bViewWillApper = NO;
		
		[loginView refreshImages];
		UIImageView *backgroundView = (UIImageView*)[self.view viewWithTag:-100];
		backgroundView.image = self.userDefaults.skin_bgLoginImg; 
		UIImageView *logoImageView = (UIImageView*)[self.view viewWithTag:-1];
		logoImageView.image = self.userDefaults.skin_loginlogoImg;
		UIImageView *titleImageView = (UIImageView*)[self.view viewWithTag:-2];
		titleImageView.image = self.userDefaults.skin_logintitleImg;
	} else {
		[self.navigationController setNavigationBarHidden:YES animated:NO];
	}
	[self hideNavigationBar];
	
	//[self.appDelegate stopActivityIndicatorView];
}

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	if (self.width < self.height) {
		[self.view viewWithTag:-200].hidden = NO;
	}
}

- (void)dealloc {
	[statJsonDao release];
	[loginView release];
	[fieldValues release];
	[imgDefault release];
    [super dealloc];
}

#pragma mark 控件动作事件

- (void)doLogin {
	if (loginView) {
		[fieldValues replaceObjectAtIndex:0 withObject:loginView.partyIdField.text];
		[fieldValues replaceObjectAtIndex:1 withObject:loginView.userIdField.text];
		[fieldValues replaceObjectAtIndex:2 withObject:loginView.pWordField.text];
	} 

	[[self findFirstResponder] resignFirstResponder];
	MServerJsonDAO *mServerDAOInstance = [[MServerJsonDAO alloc] init];
	[mServerDAOInstance initServerUrl];
	[[MServerDAO sharedInstance] loginAsync:[fieldValues objectAtIndex:0] 
									 userId:[fieldValues objectAtIndex:1]
								   password:[fieldValues objectAtIndex:2]
									   imei:[[UIDevice currentDevice] uniqueGlobalDeviceIdentifier]
									   imsi:@""
									  acode:@""
								   delegate:self];
}

- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	if (imgDefault && bAutoLogin) {
		[imgDefault removeFromSuperview];
		[self defaultInit];
	}
	if ([returnValue objectForKey:@"nck"]) {
		LoginCheckController *loginCheckController = [[LoginCheckController alloc] init];
		loginCheckController.partyId = [fieldValues objectAtIndex:0];
		loginCheckController.userId = [fieldValues objectAtIndex:1];
		loginCheckController.password = [fieldValues objectAtIndex:2];
		loginCheckController.navigationItem.hidesBackButton = YES;
		[self.navigationController pushViewController:loginCheckController animated:!bAutoLogin];
		[loginCheckController release];
	} else {
		statJsonDao.partyId = [fieldValues objectAtIndex:0];
		statJsonDao.userId = [fieldValues objectAtIndex:1];
		statJsonDao.serverUrl = self.userDefaults.current_ServerUrl;
		[statJsonDao sendStatRequest];
		
		self.userDefaults.current_PartyId = [fieldValues objectAtIndex:0];
		self.userDefaults.current_UserId = [fieldValues objectAtIndex:1];
		self.userDefaults.current_ServerUrl = self.userDefaults.current_ServerUrl;
		
		if (self.userDefaults.isSavePassword) {
			self.userDefaults.current_Password = [fieldValues objectAtIndex:2];
		}
		else {
			self.userDefaults.current_Password = @"";
		}
		
		NSMutableDictionary *loginReturn = [returnValue retain];
		
		NSString *timeStamp = [loginReturn objectForKey:@"ldt"];
		
		[[MServerConfigCache sharedInstance] loadCacheFromStore:timeStamp 
														 server:self.userDefaults.current_ServerUrl
														  party:[fieldValues objectAtIndex:0] 
														   user:[fieldValues objectAtIndex:1]];
		
		if ([returnValue objectForKey:@"sct"] && [[returnValue objectForKey:@"sct"] count] > 0) {
			MCTabBarController* tabBarController = [[[MCTabBarController alloc] init] autorelease];
			tabBarController.tabBarData = returnValue;
			[self.navigationController pushViewController:tabBarController animated:!bAutoLogin];
		} else {
			MenuController *menuViewController = [[MenuController alloc] init];
			menuViewController.title = [MCFunction getAppName];
			menuViewController.menus = [loginReturn objectForKey:@"app"];
			menuViewController.isApp = YES;
			
			menuViewController.navigationItem.hidesBackButton = YES;
			[self.navigationController pushViewController:menuViewController animated:!bAutoLogin];
			[menuViewController release];
		}
		
		[loginReturn release];
		
	}
	[imgDefault release];imgDefault=nil;
}

- (void)getServerError: (NSString *)returnCode returnMessage:(NSString *)returnMessage
{
	if (imgDefault && bAutoLogin) {
		[imgDefault removeFromSuperview];
		[self defaultInit];
		[self viewWillAppear:NO];
	}
	
	[[MCErrorManagement instance] doError:returnCode returnMessage:returnMessage];
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
	isRotate = YES;
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
	[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
	int nWidth = CGRectGetWidth(self.view.bounds);
	int nHeight = CGRectGetHeight(self.view.bounds);
	if (nWidth > nHeight) {//横屏状态
		int nPosyAddition = 0;
		if (bViewWillApper && !self.navigationController.navigationBarHidden) {
			nPosyAddition = self.userDefaults.isHidePartyId ? 15 : 35;
		}
		self.navigationController.navigationBarHidden = YES;
		int naviAddtion = navigationBarHeight - CGRectGetHeight(self.navigationController.navigationBar.frame);
		CGRect loginViewFrame = loginView.frame;
		if (self.userDefaults.isDemoApplication) {//演示应用
			loginViewFrame.size.height = kLoginFormBackgroundHeight_Demo;
		} else {
			loginViewFrame.size.height = kLoginFormBackgroundHeight_Demo;
		}
		if (self.userDefaults.isHidePartyId) {
			loginViewFrame.origin.y = nHeight-CGRectGetHeight(loginViewFrame) + 10 - nPosyAddition;
			[self.view viewWithTag:-1].hidden = NO;
		} else {
			loginViewFrame.origin.y = nHeight-CGRectGetHeight(loginViewFrame)+ 10 - nPosyAddition + (isRotate ? 0 :naviAddtion);
			[self.view viewWithTag:-1].hidden = YES;
		}

		loginView.frame = loginViewFrame;
		
	} else {
		self.navigationController.navigationBarHidden = NO;
		CGRect loginViewFrame = loginView.frame;
		loginViewFrame.origin.y = (self.height-loginViewHeight)/2+[self moveLoginViewHeight];
		//if (self.userDefaults.isDemoApplication) {//演示应用
			loginViewFrame.size.height = kLoginFormBackgroundHeight_Demo;
		//} else {
		//	loginViewFrame.size.height = kLoginFormBackgroundHeight_App;
		//}
		
		loginView.frame = loginViewFrame;
		[self.view viewWithTag:-1].hidden = NO;
	}
	
	isRotate = NO;
}

- (NSInteger)moveLoginViewHeight {
	return 0;
}

// 跳转到设置界面
-(void)showPreferences:(id)inSender {
	SettingController *settingController = [[[SettingController alloc] initWithStyle:UITableViewStyleGrouped] autorelease];
	[self.navigationController pushViewController:settingController animated:YES];
}

// 跳转到帐号界面
-(void)showAccount:(id)inSender {
	AccountController *accountController = [[[AccountController alloc] initWithStyle:UITableViewStyleGrouped] autorelease];
	[self.navigationController pushViewController:accountController animated:YES];
}

// 跳转到demo界面
-(void)showDemo:(id)inSender {	
    //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://zszw.iuni.com.cn/apple/gdei.mobileconfig"]];	

	DemoController *demoController = [[[DemoController alloc] initWithStyle:UITableViewStyleGrouped] autorelease];
	[self.navigationController pushViewController:demoController animated:YES];
}

// 跳转到help界面
-(void)showHelp:(id)inSender {
	AboutController *aboutController = [[[AboutController alloc] initWithStyle:UITableViewStyleGrouped] autorelease];
	[self.navigationController pushViewController:aboutController animated:YES];
}

#pragma mark ----键盘出现、消失时的相关处理 ----

// Called when the UIKeyboardWillShowNotification is sent.
- (void)keyboardDidShown:(NSNotification*)aNotification
{	
	@try {
		NSDictionary* info = [aNotification userInfo];
		NSValue* aValue = [info objectForKey:@"UIKeyboardBoundsUserInfoKey"];
		CGSize keyboardSize = [aValue CGRectValue].size;

		int nRowNum = [loginView.tableView numberOfRowsInSection:0];
		CGRect  pWordFieldFrame = [loginView.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:nRowNum-1 inSection:0]];
		int nStep = self.height - keyboardSize.height - CGRectGetMaxY(pWordFieldFrame) - CGRectGetMinY(loginView.frame);
		if (nStep < 0) {
			CGRect frame = loginView.frame;
			nPosy = frame.origin.y ;
			frame.origin.y += nStep;
			loginView.frame = frame;
		} else {
			nPosy = 0;
		}
	}
	@catch (NSException * e) {
		[self getServerError:@"100" returnMessage:[e reason]];
	}
}


// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardDidHidden:(NSNotification*)aNotification
{
	@try {
		if (nPosy > 0) {
			CGRect frame = loginView.frame;
			frame.origin.y = nPosy;
			loginView.frame = frame;
		}
	}
	@catch (NSException * e) {
		[self getServerError:@"100" returnMessage:[e reason]];
	}
}

@end
